package com.sjb.cp.manager.websocket.disruptor;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.sjb.cp.manager.websocket.PictureEditRequestMessage;
import com.sjb.cp.model.po.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;

/**
 * @Author:sjb
 * @CreateTime:2025-02-20
 * @Description: 事件生产者-负责将数据分发到缓冲区
 * @Version：1.0
 */
@Slf4j
@Component
public class PictureEditEventProducer {

    @Resource
    Disruptor<PictureEditEvent> pictureEditEventDisruptor;

    public void publishEvent(PictureEditRequestMessage pictureEditRequestMessage,
                             WebSocketSession session, User loginUser,Long pictureId) {
        RingBuffer<PictureEditEvent> ringBuffer = pictureEditEventDisruptor.getRingBuffer();
        long next = ringBuffer.next();
        PictureEditEvent pictureEditEvent = ringBuffer.get(next);
        pictureEditEvent.setPictureId(pictureId);
        pictureEditEvent.setSession(session);
        pictureEditEvent.setUser(loginUser);
        pictureEditEvent.setPictureEditRequestMessage(pictureEditRequestMessage);
        // 发布事件
        ringBuffer.publish(next);
    }

    /**
     * 优雅停机
     */
    @PreDestroy
    public void close() {
        pictureEditEventDisruptor.shutdown();
    }

}
